/* eslint-disable @typescript-eslint/no-use-before-define */
import React, { FC, useEffect, useState } from 'react';

import {
  NavBar,
  SearchBar,
  List,
  Checkbox,
  Modal
} from 'antd-mobile-v2';
import styles from './index.module.less';
import { GetStudentsList } from '@/services/member';
import AntdRefreshList from '@/components/antd-refresh-list';
import { connect } from 'react-redux';
import { WrappedFormClass } from 'rc-form';
import { ConnectProps } from 'typings/connect';

import { stopBodyScroll, recoverBodyScroll } from '@/utils';


const CheckboxItem = Checkbox.CheckboxItem;
const Item = List.Item;

export interface ICheckboxSelectModal extends ConnectProps {
  modalStatus: boolean;
  orgData: any;
  // recordId: string;
  form?: WrappedFormClass<{}>;
  closeModal: () => void;
  onRefreshStatus?: () => void;
  submit: (selectArray: any[]) => void;
  saveOnSubmit: boolean; // 是否在触发 submit 事件时提交数据到后台
  receiveData?: any; // 接收回填的数据（在已选数据基础上）
  resetData?: any; // 接收回填的数据（覆盖已选数据）
  mode?: 'single' | 'multiple';
  height?: number; // 虚拟列表高度
  externalOption: any;
  disabledOption?: (item: object) => boolean; // 不可选择的项目
}
interface IStudentItem {
  [index: string]: string | number;
}

const height = document.documentElement.clientHeight - document.documentElement.clientWidth * (40 + 5) / 375;

// 审批业务首页
const CheckboxSelectModal: FC<ICheckboxSelectModal> = (props) => {
  const [selectedItemObject, setSelectedItemObject] = useState<{ [key: string]: object | null }>({}); // 维护选中对象
  // const [selectedItemSet, setSelectedItemSet] = useState<Set<IStudentItem>>(new Set()); // 维护一个选中的列表
  const [searchStatus, setSearchStatus] = useState<boolean>(false);
  const [searchLoading, setSearchLoading] = useState<boolean>(false);
  const [matchSearchList, setMatchSearchList] = useState<any[]>([]);
  const [searchValue, setSearchValue] = useState<string>('');
  const [pageNum, setPageIndex] = useState<number>(1);
  const [keyword, setKeyword] = useState<string>('');
  const [visible, setVisible] = useState(false);
  const showModel = () => {

    setSearchStatus(false);
    setSelectedItemObject({});
    setMatchSearchList([]);

    setSearchValue('');
    setPageIndex(1);
    setKeyword('');
    setVisible(true);



  };

  useEffect(() => {
    let flag = false;
    if (!flag && visible) {
      requestData('', 1);
      flag = true;
      setData();
    }
  }, [visible]);
  const closeModal = () => {

    setVisible(false);
  };
  const PAGE_SIZE = 20;


  useEffect(() => {

    if (props.value) {
      const value = props.value[props.code];
      // setMatchSearchList([value]);
      const id = value.value as string;
      setSelectedItemObject({ ...{ [id]: value } });
    }

  }, [props.value]);

  useEffect(() => {

    if (props.modalStatus) {
      // console.log('stopBodyScroll');
      stopBodyScroll();
    } else {
      // console.log('recoverBodyScroll');
      recoverBodyScroll();
    }
    return () => {
      // console.log('recoverBodyScroll return');
      recoverBodyScroll();
    };
  }, [props.modalStatus]);
  const setData = () => {
    const studentCode = props.form?.getFieldValue(props.code);
    console.log('studentCode');
    console.log(studentCode);
    const obj = {};
    if (Array.isArray(studentCode) && studentCode.length) {
      // setMatchSearchList([...studentCode]);
      studentCode.forEach((item: any) => {
        obj[item.value] = item;
      });
    } else if (studentCode) {
      // setMatchSearchList([studentCode]);
      obj[studentCode.value] = studentCode;
    }
    setSelectedItemObject({ ...obj });
  };
  const requestData = async (keyword: string, pageNum: number) => {
    setSearchLoading(true);
    const data = await GetStudentsList(props.externalOption.url, keyword, pageNum, PAGE_SIZE, props.externalOption.requestParams || {});
    setSearchLoading(false);
    let list = matchSearchList;
    if (pageNum == 1) {
      list = [];
    }
    const newData = list.concat(data.data.rows);
    setMatchSearchList([...newData]);

  };



  // 点击单选框 
  const clickItemBox = (paramItem: IStudentItem) => {
    const newData = selectedItemObject;
    const id = props.externalOption?.formatVal?.value || 'id';
    const status = !newData[paramItem[id]];
    if (status) {
      newData[paramItem[id]] = paramItem;
    } else {
      newData[paramItem[id]] = null;
    }
    setSelectedItemObject({ ...newData });
    // TODO 
    // 异步加载数据之后选中列表视图不会更新，重新设置数组强制刷新视图 ，后面有时间找下原因;
    Promise.resolve().then(() => {
      setMatchSearchList([...matchSearchList]);
    });

  };

  const navToBack = () => {
    closeModal();
  };
  const getSelectArray = () => {
    const array = [];
    Object.keys(selectedItemObject).forEach((key) => {
      const item = selectedItemObject[key];
      if (item) array.push(item);
    });
    return array;
  };
  const submitSelected = () => {
    const selectArray = getSelectArray();
    if (selectArray.length) {
      props.submit && props.submit(selectArray);
    }
    navToBack();
    // setRouterActionStack([]);

    // props.closeModal && props.closeModal();
  };

  const handleLoadMore = () => {
    const currentPageIndex = pageNum + 1;
    requestData(keyword, currentPageIndex);
    setPageIndex(currentPageIndex);
  };

  const handleSearch = (val: string) => {
    setSearchValue(val);
    setMatchSearchList([]);

    if (!val) {
      return;
    }
    setKeyword(val);
    setPageIndex(1);
    requestData(val, 1);
  };

  const modal = () => {


    return (<>
      {
        (
          visible && <Modal
            className={styles.baseContainer}
            visible={visible}
            popup
            // onClose={this.onClose}
            animationType="slide-up"
          >
            <div className={styles.navBarWrap}>
              <NavBar
                mode="light"

                icon={
                  searchStatus ?
                    <span>取消</span>
                    :
                    <i className="icon iconfont">&#xe721;</i>
                }
                onLeftClick={navToBack}
              >
                {'收款人'}
              </NavBar>
            </div>
            <div className={styles.searchWrap}>
              <SearchBar
                placeholder="搜索"
                value={searchValue}
                onFocus={() => { setSearchStatus(true); }}
                onCancel={() => {
                  setSearchStatus(false); setSearchValue('');
                }}
                onChange={(val) => {
                  handleSearch(val);
                }}
              />
            </div>
            <>
              {
                matchSearchList?.length ?
                  <AntdRefreshList
                    height={window.screen.height - 102}
                    initialListSize={PAGE_SIZE}
                    dataSource={matchSearchList}
                    refreshing={false}
                    loadingMore={false}
                    showFooterText={false}
                    enableRefresh={false}
                    noMargin
                    renderRow={(item) => (
                      <Item
                        key={item[props.externalOption?.formatVal?.value]}
                        multipleLine
                      >
                        <CheckboxItem
                          key={item[props.externalOption?.formatVal?.value]}
                          disabled={props.disabledOption && props.disabledOption(item)}
                          checked={!!(selectedItemObject[(item[props.externalOption?.formatVal?.value])])}
                          onClick={(e: any) => {

                            // this.selectItem(e, item, index);
                            clickItemBox(item);
                          }}
                        >
                          <div className={styles.avatorArea}>
                            <div className={styles.userInfoBox}>
                              <h3>
                                {
                                  props.externalOption?.formatVal?.text?.split(',').map((key: string, i: number) => (item[key] && i) ? ('/' + item[key] || '') : (item[key] || '')).join('') || ''

                                }
                              </h3>

                            </div>
                          </div>
                        </CheckboxItem>
                      </Item>
                    )}
                    onEndReached={handleLoadMore}
                  />

                  : searchValue && !searchLoading ?
                    <p className={styles.noSearch}>没有找到“<span style={{ color: '#D2022A' }}>{searchValue}</span>”相关结果</p>
                    : ''
              }
            </>

            <div className={styles.ensureButtonWrap}>
              <span
                key="ensure"
                className={styles.ensureButton}
                onClick={submitSelected}
              >
                确定({getSelectArray().length})
              </span>
            </div>
          </Modal>
        )
      }
    </>);
  };
  const extra = () => {
    const selectArray = getSelectArray();
    if (selectArray.length) {
      const data = selectArray.map((item, index) => {
        const text = item.text ? item.text : props.externalOption?.formatVal?.text?.split(',').map((key: string, i: number) => (item[key] && i) ? ('/' + item[key] || '') : item[key] || '').join('') || '';
        return <div className={styles['receiver']} key={item[props.externalOption?.formatVal?.value] || index} >
          {
            text
          }
        </div >;
      });
      return (
        <div className={styles.extraContainer}>
          {
            data
          }
        </div>
      );
    } else {
      return <span style={{ color: '#B8B8B8' }}>请选择</span>;
    }

  };

  const fieldProps = () => {
    const { getFieldProps } = props.form || {};
    if (getFieldProps) {



      const data = {
        ...getFieldProps(props.code, {
          rules: [{ required: props.required, message: `请选择${props.name}` }]
        })
      };

      return {
        data
      };
    }
    return {};
  };



  return (
    <>
      <List.Item
        arrow="horizontal"
        extra={extra()}
        {...fieldProps()}
        onClick={showModel}

      >
        {props.name}
      </List.Item>
      {modal()}
    </>

  );
};

export default connect()(CheckboxSelectModal);

